package store

import (
	"gitee.com/zaiqiang231/lovesport-user-service/app/model"
	"gitee.com/zaiqiang231/lovesport-user-service/app/model/req"
	"gorm.io/gorm"
)

type ApiStore struct {
	db *gorm.DB
}

func (receiver ApiStore) Execute(runnable Runnable) {
	runnable(receiver.db)
}

func (receiver ApiStore) Get(id uint) (result model.SysApi, err error) {
	err = receiver.db.Where("id = ?", id).First(&result).Error
	return
}

func (receiver ApiStore) Create(req *model.SysApi) error {
	return receiver.db.Create(req).Error
}

func (receiver ApiStore) Delete(req *model.SysApi, isSoftDelete bool) error {
	var err error
	if isSoftDelete {
		err = receiver.db.Delete(req).Error
	} else {
		err = receiver.db.Unscoped().Delete(req).Error
	}
	return err
}

func (receiver ApiStore) Update(req *model.SysApi) error {
	return receiver.db.Save(req).Error
}

func (receiver ApiStore) List(opts req.PageInfo) (*ApiList, error) {
	list := &ApiList{}
	err := receiver.db.
		Offset((opts.Page - 1) * opts.PageSize).
		Limit(opts.PageSize).
		Find(&list.List).
		Offset(-1).
		Limit(-1).
		Count(&list.Total).Error
	if err != nil {
		return nil, err
	}
	return list, nil
}

type ApiList struct {
	Total int64          `json:"total"`
	List  []model.SysApi `json:"list"`
}
